﻿using System;
using SharpArch.Core.DomainModel;
using SharpArch.Core.PersistenceSupport;

namespace good1.Core.Mapper
{


    public abstract class GoodMapper<TModel, TMessage> : IGoodMapper<TModel, TMessage> where TModel : Entity, new()
    {
        private readonly IRepository<TModel> repository;

        protected GoodMapper(IRepository<TModel> repository)
        {
            this.repository = repository;
        }

        public abstract TK Map<T, TK>(T model);

        public virtual TMessage Map(TModel model)
        {
            return Map<TMessage>(model);
        }

        public TMessage2 Map<TMessage2>(TModel model)
        {
            return Map<TModel, TMessage2>(model);
        }

        public virtual TModel Map(TMessage message)
        {
            TModel model = repository.Get(GetIdFromForm(message)) ?? new TModel();
            MapToModel(message, model);
            return model;
        }

        protected abstract int GetIdFromForm(TMessage message);
        protected abstract void MapToModel(TMessage message, TModel model);

        protected static DateTime? ToDateTime(string value)
        {
            DateTime result;
            bool success = DateTime.TryParse(value, out result);
            if (!success)
            {
                return null;
            }
            return result;
        }
    }
}
